package com.wuliming.gulimall.product.service.impl;

import cn.hutool.core.util.StrUtil;
import com.wuliming.constant.ProductConstant;
import com.wuliming.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.wuliming.gulimall.product.dao.AttrDao;
import com.wuliming.gulimall.product.entity.*;
import com.wuliming.gulimall.product.entity.vo.req.AttrReqVo;
import com.wuliming.gulimall.product.entity.vo.resp.AttrRespVo;
import com.wuliming.gulimall.product.service.AttrGroupService;
import com.wuliming.gulimall.product.service.CategoryService;
import com.wuliming.gulimall.product.service.ProductAttrValueService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuliming.common.utils.PageUtils;
import com.wuliming.common.utils.Query;

import com.wuliming.gulimall.product.service.AttrService;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveDetail(AttrReqVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        save(attrEntity);
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrSort(0);
            relationDao.insert(relationEntity);
        }
    }

    @Override
    public PageUtils queryListPage(Map<String, Object> params, Long catelogId, String type) {
        int attrType = "base".equalsIgnoreCase(type) ? 1 : 0;
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type", attrType);
        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (StrUtil.isNotEmpty(key)) {
            wrapper.and(w -> w.eq("attr_id", key).or().like("attr_name", key));
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        List<AttrRespVo> respVoList = page.getRecords().stream().map(w -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(w, attrRespVo);
            if (w.getAttrType().equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())) {
                AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>
                        ().eq("attr_id", w.getAttrId()));
                if (Objects.nonNull(relationEntity) && Objects.nonNull(relationEntity.getAttrGroupId())) {
                    AttrGroupEntity groupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                    attrRespVo.setGroupName(groupEntity.getAttrGroupName());
                }
            }
            CategoryEntity categoryEntity = categoryService.getById(w.getCatelogId());
            if (Objects.nonNull(categoryEntity)) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(respVoList);
        return pageUtils;
    }

    @Override
    public AttrRespVo getByIdInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        if (attrEntity.getAttrType().equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())) {
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (Objects.nonNull(relationEntity)) {
                AttrGroupEntity groupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                if (Objects.nonNull(groupEntity)) {
                    attrRespVo.setAttrName(groupEntity.getAttrGroupName());
                    attrRespVo.setAttrGroupId(groupEntity.getAttrGroupId());
                }
            }
        }
        if (attrEntity.getCatelogId() != null) {
            Long[] catelogPath = categoryService.getCatelogPath(attrEntity.getCatelogId());
            attrRespVo.setCatelogPath(catelogPath);
            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        return attrRespVo;
    }

    @Override
    public void updateDetail(AttrReqVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());
            wrapper.eq("attr_id", attr.getAttrId());
            Long count = relationDao.selectCount(wrapper);
            if (count > 0) {
                relationDao.update(relationEntity, wrapper);
            } else {
                relationDao.insert(relationEntity);
            }
        }
    }

    @Override
    public List<ProductAttrValueEntity> listforspu(Long spuId) {
        return productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        List<AttrEntity> list = list(new QueryWrapper<AttrEntity>().in("attr_id", attrIds)
                .eq("search_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()));
        return list.stream().map(AttrEntity::getAttrId).collect(Collectors.toList());
    }


}